const TestItem = require('../models/testItem')
const setOutput = require('../tools/setOutput').setOutput
const standardObj = require('../tools/setOutput').standardObj
class TestTypeController {
  prefix = '' 
  getPath(name){
    return name ? `/${this.prefix}/${name}` : `/${this.prefix}`
  }  

  async find(ctx, next) {
    const {page = 1, pageSize = 20} = ctx.request.query 
    const total = await TestItem.count({})
    const list = await TestItem.find().sort({createdTime: -1}).skip((parseInt(page) - 1) * parseInt(pageSize)).limit(parseInt(pageSize) || 5).lean()
    const data = {
      list: list,
      total: total
    }
    ctx.response.body = setOutput(data, 'fetch')
  }

  async add(ctx, next){  
    ctx.verifyParams({
      title: { type: "string", required: true }
    })
    let obj = {...ctx.request.body}
    
    const [err, data] = await to(new TestItem(obj).save())
    if(err) return ctx.throw(500, err)
    ctx.response.body = setOutput(data.toJSON())  

  }

  async calcItemCount(ctx, next) {
    const arr = [
      {
        '$unwind': '$types'
      },
      {
        '$group': {
          '_id': '$types', 
          'count': {'$sum': 1}
        }
      }
    ]

    const countList = await TestItem.aggregate(arr)
    // console.log('countList', countList)
    ctx.response.body = {
      data: countList,
      code: 0,
      msg: '成功'
    }
  }
}


module.exports = new TestTypeController()